import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Dialog } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useState } from 'react';
import DataForm from './components/DataForm';
import { column, ENUMS } from './stores/definitions';
import { toJS } from 'mobx';
import AddConsoleUser from './components/AddConsoleUser';

const tableId = uniqueId('tauTable-');
const { confirm } = Dialog;

const User = () => {
  const [modal, setModal] = useState({
    show: null,
    record: null,
  });
  const { userStore: store } = useStore();

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { ...searchArgs } = params.values;
    store.search = {
      ...searchArgs,
    };
  };

  // 点击打开添加
  const handleOpenAdd = () => {
    setModal({
      show: 'add',
      record: null,
    });
  };

  // 添加平台用户
  const handleOpenAddPF = () => {
    setModal({
      show: 'addHT',
      record: null,
    });
  };

  // 点击打开编辑
  const handleOpenEdit = (record) => {
    setModal({
      show: 'edit',
      record,
    });
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal({
      show: null,
      record: null,
    });
  };

  // 查看用户
  const handleViewUser = (record) => {
    setModal({
      show: 'view',
      record,
    });
  };

  // 删除用户
  const handelDelete = (user) => {
    confirm({
      content: t`确认删除该客户吗?`,
      onOk() {
        return store.deleteUser(user.username);
      },
    });
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const tempResult = _.cloneDeep(toJS(result));
        tempResult.userTypes.push(100);
        const curUserTypes = [...new Set(tempResult.userTypes)];
        tempResult.userTypes = curUserTypes;
        await store.update(toJS(tempResult));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const tempResult = _.cloneDeep(toJS(result));
        tempResult.userTypes.push(100);
        await modal.show === 'pf' ? store.update(tempResult) : store.create(tempResult);
        Message.success({ content: t`用户创建成功` });
      } catch (e) {
        Message.error({ content: t`用户创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-addUser',
            title: t`添加后台用户`,
            type: 'primary',
            onClick: handleOpenAdd,
          },
          {
            name: 'btn-addPFUser',
            title: t`平台用户添加身份`,
            type: 'primary',
            onClick: handleOpenAddPF,
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="username"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.user)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('accountId', {
              cell: (v, _, r) => <Button text type="primary" onClick={() => handleViewUser(r)} >{v}</Button>,
            }),
            column('fullname', { width1: 58 }),
            column('mobile', { width1: 58 }),
            column('email', { width1: 88 }),
            column('status', { width: 88 }),
            column('lastLogin', { width1: 68 }),
            column('roles', { width1: 68 }),
            {
              title: t`操作`,
              dataIndex: 'xcxUserNumber',
              width: 180,
              cell: (_, __, user) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenEdit(user)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" style={{ color: 'red' }} onClick={() => handelDelete(user)} >{t`删除`}</Button>
                </>),
            },
          ]}
        />
      </div>
      <Drawer
        visible={modal.show === 'add' || modal.show === 'edit' || modal.show === 'view'}
        title={ENUMS._USERS[modal.show]}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, toClose: `toClose$${Date.now()}` })}
        width="600px"
      >
        <AddConsoleUser
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal.show === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Drawer
        visible={modal.show === 'addHT'}
        title={ENUMS._PLAT_USERS[modal.show]}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, toClose: `toClose$${Date.now()}` })}
        width="600px"
      >
        <DataForm
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal.show === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
    </TauPage>
  );
};

export default observer(User);
